package com.astrofizzbizz.stoneedgegui.app;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Icon;

import com.astrofizzbizz.stoneedgegui.monitor.DomeMonitorPanelActionListeners;
import com.astrofizzbizz.stoneedgegui.utilities.StoneEdgeIIIException;
import com.astrofizzbizz.stoneedgegui.utilities.TreffersLock;


public class TelescopeLockDialog extends JDialog
{
	private static final long serialVersionUID = 6386403398691959806L;
	private StoneEdgeIIIGui stoneEdgeIIIGui;
	private TreffersLock treffersLock = null;

	private JTextField userName = new JTextField("");
	private JTextField emailAddress = new JTextField("");
	private JTextField phoneNumber = new JTextField("");
	private JTextField comment = new JTextField("");
	private JButton lockButton = new JButton("Lock");
	private JButton unlockButton = new JButton("Unlock");
	private JButton cancelButton = new JButton("Cancel");
	private String[] backDoor1 = {"d", "dmcginnis427@gmail.com", "6304574205"};
	private String[] backDoor2 = {"v", "vhoette@yerkes.uchicago.edu", "2622151599"};
    
	private ImageIcon yodaImageIcon;
	private ImageIcon lockIcon;
	private ImageIcon unlockIcon;
	private ImageIcon batPhoneIcon;
	private ActionEventButton lockChangedButton = null;

	protected TelescopeLockDialog(StoneEdgeIIIGui stoneEdgeIIIGui) throws StoneEdgeIIIException
	{
		super(stoneEdgeIIIGui, true);
		this.stoneEdgeIIIGui = stoneEdgeIIIGui;
		setTitle("Telescope Lock");
		
		lockChangedButton = new ActionEventButton("");
		lockChangedButton.addActionListener(new DomeMonitorPanelActionListeners("Lock.Changed", stoneEdgeIIIGui.getTelescopeMonitorPanel().getDomeMonitorPanel()));
		
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		String iconLoc = "com/astrofizzbizz/stoneedgegui/files/StoneEdgeTelescopeLogo.jpg";
		URL resourceURL = loader.getResource(iconLoc);
        setIconImage(new ImageIcon(resourceURL).getImage());
		iconLoc = "com/astrofizzbizz/stoneedgegui/files/yoda.jpg";
		resourceURL = loader.getResource(iconLoc);
		yodaImageIcon = new ImageIcon(resourceURL);
		iconLoc = "com/astrofizzbizz/stoneedgegui/files/stock_lock.jpg";
		resourceURL = loader.getResource(iconLoc);
		lockIcon = new ImageIcon(resourceURL);
		iconLoc = "com/astrofizzbizz/stoneedgegui/files/stock_lock_open.jpg";
		resourceURL = loader.getResource(iconLoc);
		unlockIcon = new ImageIcon(resourceURL);
		iconLoc = "com/astrofizzbizz/stoneedgegui/files/batphone.jpg";
		resourceURL = loader.getResource(iconLoc);
		batPhoneIcon = new ImageIcon(resourceURL);
      
        
		boolean telescopeLocked = false;
		try 
		{
			treffersLock = new TreffersLock(stoneEdgeIIIGui.getStoneEdgeIIITunnel());
		} catch (StoneEdgeIIIException e) {
			e.messageDialog(this);
	        setVisible(false);
	        throw new StoneEdgeIIIException(e.getMessage());
		}
		userName.setText(treffersLock.getEmailName());
		emailAddress.setText(treffersLock.getEmail());
		phoneNumber.setText(treffersLock.getPhone());
		comment.setText(treffersLock.getEmailName());
		telescopeLocked = treffersLock.isLock();
 
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
        mainPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(""),BorderFactory.createEmptyBorder(5,5,5,5)));
        
        mainPanel.add(messagePanel(telescopeLocked));
        mainPanel.add(userInfoPanel(telescopeLocked));
        mainPanel.add(buttonPanel(telescopeLocked));
		getContentPane().add(mainPanel);
		
        pack();
        setLocationRelativeTo(stoneEdgeIIIGui);
        setVisible(true);
        
	}
	private JPanel userInfoPanel(boolean telescopeLocked)
	{

		JPanel labelPanel = new JPanel();
		labelPanel.setLayout(new GridLayout(4,1));
		labelPanel.add(new JLabel("User Name "));
		labelPanel.add(new JLabel("Email Address "));
		labelPanel.add(new JLabel("Phone Number "));
		labelPanel.add(new JLabel("Comment "));
		
		JPanel textPanel = new JPanel();
		textPanel.setLayout(new GridLayout(4,1));
		userName.setEditable(false);
		userName.setColumns(20);
		textPanel.add(userName);
		textPanel.add(emailAddress);
		textPanel.add(phoneNumber);
		textPanel.add(comment);
		if (telescopeLocked)
		{
			userName.setEditable(false);
			emailAddress.setEditable(false);
			phoneNumber.setEditable(false);
			comment.setEditable(false);
		}
		else
		{
			userName.setEditable(false);
			emailAddress.setEditable(true);
			phoneNumber.setEditable(true);
			comment.setEditable(false);
		}
		
		JPanel userInfoPanel = new JPanel();
		userInfoPanel.setLayout(new BoxLayout(userInfoPanel, BoxLayout.X_AXIS));
		userInfoPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(""),BorderFactory.createEmptyBorder(5,5,5,5)));
		userInfoPanel.add(labelPanel);
		userInfoPanel.add(textPanel);
		return userInfoPanel;
	}
	private JPanel buttonPanel(boolean telescopeLocked)
	{
        lockButton.addActionListener(new TelescopeLockDialogActionListeners("lockButton", this));
        unlockButton.addActionListener(new TelescopeLockDialogActionListeners("unlockButton", this));
        cancelButton.addActionListener(new TelescopeLockDialogActionListeners("cancelButton", this));
        
        lockButton.setForeground(Color.green);
        unlockButton.setForeground(Color.red);
		
		JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
		buttonPanel.add(lockButton);
		buttonPanel.add(unlockButton);
		buttonPanel.add(cancelButton);
		if (telescopeLocked)
		{
			lockButton.setVisible(false);
			unlockButton.setVisible(true);
		}
		else
		{
			lockButton.setVisible(true);
			unlockButton.setVisible(false);
		}
		return buttonPanel;
	}
	private JPanel messagePanel(boolean telescopeLocked)
	{
		JLabel message = new JLabel("Telescope Locked!");
		message.setForeground(Color.RED);
		if (!telescopeLocked)
		{
			message = new JLabel(unlockIcon);
			message.setText("Telescope Unlocked");
			message.setForeground(Color.BLUE);
		}
		else
		{
			if (stoneEdgeIIIGui.getUserKey().equals(treffersLock.getSessionID()))
			{
				message = new JLabel(yodaImageIcon);
				message.setText("You have Ultimate Power!");
				message.setForeground(Color.BLUE);
			}
			else
			{
				message = new JLabel(lockIcon);
				message.setText("Telescope Locked");
				message.setForeground(Color.RED);
			}
		}

		JPanel messagePanel = new JPanel();
		messagePanel.setLayout(new BoxLayout(messagePanel, BoxLayout.X_AXIS));

		messagePanel.add(message);
		return messagePanel;
	}
	void setLock()
	{
		String phoneEntry = phoneNumber.getText();
		String emailEntry = emailAddress.getText();
		if (emailEntry.equals(backDoor1[0]))
		{
			emailEntry = backDoor1[1];
			phoneEntry = backDoor1[2];
		}
		if (emailEntry.equals(backDoor2[0]))
		{
			emailEntry = backDoor2[1];
			phoneEntry = backDoor2[2];
		}
		boolean phoneEntryOk = false;
		if (phoneEntry.replaceAll(" ", "").length() > 0)
		{
			phoneEntryOk = true;
		}
		else
		{
			JOptionPane.showMessageDialog(this,"Bad Phone Number","Error",JOptionPane.ERROR_MESSAGE);
		}
		boolean emailEntryOk = false;
		if (emailEntry.replaceAll(" ", "").length() > 0) 
		{
			if (emailEntry.indexOf("@") > 0)
			{
				emailEntryOk = true;
			}
			else
			{
				JOptionPane.showMessageDialog(this,"Bad Email Address","Error",JOptionPane.ERROR_MESSAGE);
			}
		}
		else
		{
			JOptionPane.showMessageDialog(this,"Bad Email Address","Error",JOptionPane.ERROR_MESSAGE);
		}
		
		if (phoneEntryOk && emailEntryOk)
		{
			try 
			{
				treffersLock.setLock(stoneEdgeIIIGui.getUserKey(), phoneEntry, emailEntry);
				System.out.println("Telescope Locked");
			} catch (StoneEdgeIIIException e) {
				e.messageDialog(this);
		        setVisible(false);
			}

			JOptionPane.showMessageDialog(this,"You have ultimate power!","Telescope Locked", getDefaultCloseOperation(), (Icon) yodaImageIcon);
			setVisible(false);
			lockChangedButton.processEvent(new ActionEvent(lockChangedButton, 1001, "locked")); // Here the event is fired  
		}

	}
	void unLock()
	{
		if (stoneEdgeIIIGui.getUserKey().equals(treffersLock.getSessionID()))
		{
			try {
				treffersLock.clearLock();
				JOptionPane.showMessageDialog(this,"Telescope Unlocked","Telescope Unlocked", getDefaultCloseOperation(), (Icon) unlockIcon);
				setVisible(false);
				lockChangedButton.processEvent(new ActionEvent(lockChangedButton, 1002, "unlocked")); // Here the event is fired  
			} catch (StoneEdgeIIIException e) {
				e.messageDialog(this);
		        setVisible(false);
			}
		}
		else
		{
			//Custom button text
			Object[] options = {"Open Lock",
			                    "Cancel"};
			int ichoice = JOptionPane.showOptionDialog(this,
			    "Lock is held by: \nEmail: " + treffersLock.getEmail() + "\nPhone: " + treffersLock.getPhone() + "\nPlease contact before breaking",
			    "Break Lock",
			    JOptionPane.YES_NO_OPTION,
			    JOptionPane.QUESTION_MESSAGE,
			    (Icon) batPhoneIcon,
			    options,
			    options[1]);	
			if (ichoice == 0)
			{
				try {
					treffersLock.clearLock();
					JOptionPane.showMessageDialog(this,"Telescope Unlocked","Telescope Unlocked", getDefaultCloseOperation(), (Icon) unlockIcon);
					setVisible(false);
					lockChangedButton.processEvent(new ActionEvent(lockChangedButton, 1002, "unlocked")); // Here the event is fired  
				} catch (StoneEdgeIIIException e) {
					e.messageDialog(this);
			        setVisible(false);
				}
			}
			else
			{
		        setVisible(false);
			}
		}
		
	}
	private class TelescopeLockDialogActionListeners implements ActionListener
	{
		String actionString = "";
		TelescopeLockDialog stoneEdgeIIIGuiLoginDialog;
		TelescopeLockDialogActionListeners(String actionString, TelescopeLockDialog stoneEdgeIIIGuiLoginDialog)
		{
			this.actionString = actionString;
			this.stoneEdgeIIIGuiLoginDialog = stoneEdgeIIIGuiLoginDialog;
		}
		@Override
		public void actionPerformed(ActionEvent arg0) 
		{
			if (actionString.equals("cancelButton"))
			{
				System.out.println("Lock Canceled");
				stoneEdgeIIIGuiLoginDialog.setVisible(false);
			}
			if (actionString.equals("lockButton"))
			{
				setLock();
			}
			if (actionString.equals("unlockButton"))
			{
				unLock();
			}
		}
	}
}
